package com.example.application2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class TheardDemoActivity extends AppCompatActivity {
    static final String UPPER_NUM = "upper";
    EditText input;
    CalThead calThead;

    class CalThead extends Thread {
        public Handler handler;
        @SuppressLint("HandlerLeak")
        public void run() {
            Looper.prepare();
            handler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    if (msg.what == 0x123){
                        List<Integer> nums = new ArrayList<>();
                        int upper = msg.getData().getInt(UPPER_NUM);
                        outer:
                        for (int i = 2; i <= upper; i++){
                            for (int j = 2; j <= Math.sqrt(i); j++){
                                if (i != 2 && i % j == 0) {
                                    continue outer;
                                }
                            }
                            nums.add(i);
                        }
                        Toast.makeText(TheardDemoActivity.this, nums.toString(),Toast.LENGTH_LONG).show();
                    }
                }
            };
            Looper.loop();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_theard_demo);
        input = findViewById(R.id.input);
        calThead = new CalThead();
        calThead.start();
    }

    public void cal(View view) {
        Message msg = new Message();
        msg.what = 0x123;
        Bundle bundle = new Bundle();
        bundle.putInt(UPPER_NUM , Integer.parseInt(input.getText().toString()));
        msg.setData(bundle);
        calThead.handler.sendMessage(msg);
    }
}